package boot

import (
	"net/http"
	"proxy_resource_test/utils/logging"
	"time"

	"github.com/smallnest/rpcx/server"
	"proxy_resource_test/internal/app"
	"proxy_resource_test/middleware"
	"proxy_resource_test/rpcx_plugins"
)

// RPCService 描述要注册的 RPC 服务
type RPCService struct {
	Name    string
	Service interface{}
}

// Option 是 functional option 类型
type Option func(*bootApp)

// WithHTTPRouter 注入 HTTP 路由
func WithHTTPRouter(router http.Handler) Option {
	return func(b *bootApp) {
		b.httpHandler = router
	}
}

// WithRPCServices 注入 RPC 服务列表
func WithRPCServices(services []RPCService) Option {
	return func(b *bootApp) {
		b.rpcServices = services
	}
}

// bootApp 实现 app.App
type bootApp struct {
	httpHandler http.Handler
	rpcServices []RPCService
}

// New 构造并返回 app.App
func New(opts ...Option) app.App {
	// 初始化 rpcx Server
	rpcSrv := server.NewServer(
		server.WithReadTimeout(30*time.Second),
		server.WithWriteTimeout(30*time.Second),
		server.WithPool(1000, 10000),
	)
	rpcSrv.AuthFunc = middleware.Auth()
	rpcSrv.Plugins.Add(&rpcx_plugins.IpMethodCounter{})

	// 构造 bootApp，并应用可选项
	b := &bootApp{
		httpHandler: http.DefaultServeMux,
	}
	for _, opt := range opts {
		opt(b)
	}

	// 注册 RPC 服务
	for _, svc := range b.rpcServices {
		rpcSrv.RegisterName(svc.Name, svc.Service, "")
	}

	logging.Info("bootApp init success")
	// 返回封装好的 Servers
	return &app.Servers{
		HTTPHandler: b.httpHandler,
		RPCServer:   rpcSrv,
	}
}
